'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
const orderCollection = db.collection('xxf-orders');
const proCollection = db.collection('xxf-products');
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event);
	const {
		uid,
		action
	} = event;
	if (!uid && action) {
		return {
			msg: '用户ID参数错误！',
			code: 0,
			data: null
		};
	}
	switch (action) {
		case 'getMineData':
			return getMineData(event);
		case 'getSevenDayList':
			return getSevenDayList(event);
		case 'getShippingList':
			return getShippingList(event);
		case 'getAllList':
			return getAllList(event);
		case 'doDataScript':
			return doDataScript(event);

		default:
			return {
				msg: 'Invalid action！',
					code: 0,
					data: null
			};
	}
};

async function doDataScript(params) {
	// 新字段的名称和默认值

	// 更新操作
	const res = await proCollection.where({}).update(
		// 更新操作，添加新字段并设置默认值
		{
			sort: 0,
			type: 1
		}
	);
	console.log('doDataScript：', res);
	if (res && res.updated === 1) {
		return {
			msg: 'success',
			code: 1,
			data: res,
		}
	} else {
		return {
			msg: 'fail',
			code: 2,
			data: res,
		}
	};
}

async function getAllList(params) {
	const listRes = await orderCollection.orderBy('create_time', 'desc').get();
	return {
		msg: 'success',
		code: 1,
		data: listRes.data || [],
	}
}

async function getShippingList(params) {
	const listRes = await orderCollection.orderBy('create_time', 'desc').where({
		status: '2',
	}).get();
	return {
		msg: 'success',
		code: 1,
		data: listRes.data || [],
	}
}

async function getSevenDayList(params) {
	const {
		uid,
	} = params;
	// 1-待支付；2-已支付；3-已发货；4-已收货；5-已失效；6-已退款；7-已取消；
	// 获取当前时间
	const now = Date.now();
	// 计算7天范围内的时间
	const sevenDaysAgo = new Date((now - 7 * 24 * 60 * 60 * 1000)).getTime();
	let sevenDaysArr = [new Date(now).getDate()];
	for (let i = 1; i < 7; i++) {
		const day = new Date((now - i * 24 * 60 * 60 * 1000)).getDate();
		sevenDaysArr.unshift(day);
	}
	const $ = db.command.aggregate;
	// 查询近7日每日的下单量 
	const sevenAllOrdersRes = await orderCollection.aggregate()
		.match({
			create_time: {
				$gte: sevenDaysAgo, // 大于或等于7天前的日期
				$lte: now // 小于或等于当前日期
			}
		})
		.group({
			_id: dbCmd.aggregate.dayOfMonth(dbCmd.aggregate.add([new Date(0), "$create_time"])),
			totalVolume: dbCmd.aggregate.sum(1)
		})
		.end();
	console.log('sevenAllOrdersRes: ', sevenAllOrdersRes);
	let sevenAllOrdersArr = [];
	if (sevenAllOrdersRes && sevenAllOrdersRes.data && sevenAllOrdersRes.data.length) {
		for (let i = 0; i < sevenDaysArr.length; i++) {
			let count_all_order = 0;
			for (let j = 0; j < sevenAllOrdersRes.data.length; j++) {
				if (sevenAllOrdersRes.data[j] && sevenDaysArr[i] === sevenAllOrdersRes.data[j]._id) {
					count_all_order = sevenAllOrdersRes.data[j].totalVolume || 0;
				}
			}
			sevenAllOrdersArr.push(count_all_order);
		}
	}
	console.log('sevenAllOrdersArr: ', sevenAllOrdersArr);
	// 查询近7日每日的成交量
	const sevenOrderRes = await orderCollection.aggregate()
		.match({
			status: dbCmd.in(['2', '3', '4']),
			create_time: {
				$gte: sevenDaysAgo,
				$lte: now
			}
		})
		.group({
			_id: dbCmd.aggregate.dayOfMonth(dbCmd.aggregate.add([new Date(0), "$create_time"])),
			totalVolume: dbCmd.aggregate.sum(1)
		})
		.end();
	console.log('sevenOrderRes: ', sevenOrderRes);
	let sevenOrdersArr = [];
	if (sevenOrderRes && sevenOrderRes.data && sevenOrderRes.data.length) {
		for (let i = 0; i < sevenDaysArr.length; i++) {
			let count_order = 0;
			for (let j = 0; j < sevenOrderRes.data.length; j++) {
				if (sevenOrderRes.data[j] && sevenDaysArr[i] === sevenOrderRes.data[j]._id) {
					count_order = sevenOrderRes.data[j].totalVolume || 0;
				}
			}
			sevenOrdersArr.push(count_order);
		}
	}
	console.log('sevenOrdersArr: ', sevenOrdersArr);
	// 查询近7日每日的成交产品数
	const sevenProsRes = await orderCollection.aggregate()
		.match({
			status: dbCmd.in(['2', '3', '4']),
			create_time: {
				$gte: sevenDaysAgo,
				$lte: now
			}
		})
		.group({
			_id: dbCmd.aggregate.dayOfMonth(dbCmd.aggregate.add([new Date(0), "$create_time"])),
			totalVolume: dbCmd.aggregate.sum('$total_count')
		})
		.end();
	console.log('sevenProsRes: ', sevenProsRes);
	let sevenProsArr = [];
	if (sevenProsRes && sevenProsRes.data && sevenProsRes.data.length) {
		for (let i = 0; i < sevenDaysArr.length; i++) {
			let count_pro = 0;
			for (let j = 0; j < sevenProsRes.data.length; j++) {
				if (sevenProsRes.data[j] && sevenDaysArr[i] === sevenProsRes.data[j]._id) {
					count_pro = sevenProsRes.data[j].totalVolume || 0;
				}
			}
			sevenProsArr.push(count_pro);
		}
	}
	console.log('sevenProsArr: ', sevenProsArr);
	// 查询近7日每日的营业额
	const sevenMoneyRes = await orderCollection.aggregate()
		.match({
			status: dbCmd.in(['2', '3', '4']),
			create_time: {
				$gte: sevenDaysAgo,
				$lte: now
			}
		})
		.group({
			_id: dbCmd.aggregate.dayOfMonth(dbCmd.aggregate.add([new Date(0), "$create_time"])),
			totalVolume: dbCmd.aggregate.sum('$need_money')
		})
		.end();
	console.log('sevenMoneyRes: ', sevenMoneyRes);
	let sevenMoneyArr = [];
	if (sevenMoneyRes && sevenMoneyRes.data && sevenMoneyRes.data.length) {
		for (let i = 0; i < sevenDaysArr.length; i++) {
			let count_money = 0;
			for (let j = 0; j < sevenMoneyRes.data.length; j++) {
				if (sevenMoneyRes.data[j] && sevenDaysArr[i] === sevenMoneyRes.data[j]._id) {
					count_money = (sevenMoneyRes.data[j].totalVolume / 100).toFixed(2);
				}
			}
			sevenMoneyArr.push(count_money);
		}
	}
	console.log('sevenMoneyArr: ', sevenMoneyArr);
	// 查询近7日每日的退款量
	const sevenRefundRes = await orderCollection.aggregate()
		.match({
			status: dbCmd.in(['6']),
			create_time: {
				$gte: sevenDaysAgo,
				$lte: now
			}
		})
		.group({
			_id: dbCmd.aggregate.dayOfMonth(dbCmd.aggregate.add([new Date(0), "$create_time"])),
			totalVolume: dbCmd.aggregate.sum(1)
		})
		.end();
	console.log('sevenRefundRes: ', sevenRefundRes);
	let sevenRefundArr = [];
	if (sevenRefundRes && sevenRefundRes.data && sevenRefundRes.data.length) {
		for (let i = 0; i < sevenDaysArr.length; i++) {
			let count_refund = 0;
			for (let j = 0; j < sevenRefundRes.data.length; j++) {
				if (sevenRefundRes.data[j] && sevenDaysArr[i] === sevenRefundRes.data[j]._id) {
					count_refund = (sevenRefundRes.data[j].totalVolume / 100).toFixed(2);
				}
			}
			sevenRefundArr.push(count_refund);
		}
	}
	console.log('sevenRefundArr: ', sevenRefundArr);
	return {
		msg: 'success',
		code: 1,
		data: {
			sevenDays: sevenDaysArr,
			sevenMoney: sevenMoneyArr,
			sevenAllOrders: sevenAllOrdersArr,
			sevenOrders: sevenOrdersArr,
			sevenPros: sevenProsArr,
			sevenRefund: sevenRefundArr
		}
	};
}

async function getMineData(params) {
	const {
		uid,
	} = params;
	// 1-待支付；2-已支付；3-已发货；4-已收货；5-已失效；6-已退款；7-已取消；
	let today = new Date();
	orderCollection.where({
		create_time: dbCmd.gte(today),
		status: '6',
	}).count()
	today.setHours(0, 0, 0, 0); // 设置到今天凌晨
	today = new Date(today).getTime();

	const [todaySalesRes, totalProRes, shippingRes, onTheWayRes, refundRes] = await Promise.all([
		orderCollection.where({
			create_time: dbCmd.gte(today),
			status: dbCmd.or(dbCmd.eq('2'), dbCmd.eq('3'), dbCmd.eq('4')),
		}).get(),
		proCollection.where({
			status: dbCmd.neq(-1),
		}).count(),
		orderCollection.where({
			status: '2',
		}).count(),
		orderCollection.where({
			status: '3',
		}).count(),
		orderCollection.where({
			create_time: dbCmd.gte(today),
			status: '6',
		}).count()
	]);
	// 今日营业数据
	console.log('todaySalesRes: ', todaySalesRes);
	// 计算今日营业额
	let todaySalesMoney = 0;
	todaySalesRes.data.forEach(order => {
		todaySalesMoney += order.pay_money;
	});
	console.log('todaySalesRes: ', todaySalesRes);
	// 在售商品
	console.log('totalProRes: ', totalProRes);
	// 发货待处理
	console.log('shippingRes: ', shippingRes);
	// 在途单
	console.log('onTheWayRes: ', onTheWayRes);
	// 今日退款
	console.log('refundRes: ', refundRes);
	return {
		msg: 'success',
		code: 1,
		data: {
			todaySalesNum: todaySalesRes.data.length || 0,
			todaySalesMoney: todaySalesMoney || 0,
			totalProNum: totalProRes.total || 0,
			shippingNum: shippingRes.total || 0,
			onTheWayNum: onTheWayRes.total || 0,
			refundNum: refundRes.total || 0,
		}
	};
}